export function TimeHandle() {
  /**
   * 将时间格式化为 format 指定的日期格式
   *
   * @param {number} format
   *
   * @return 返回指定格式的日期
   * 默认返回：YYYY年MM月DD
   */
  const formatDate = (format) => {
    const date = new Date()

    const year = date.getFullYear()
    const month = `0${date.getMonth() + 1}`.slice(-2)
    const day = `0${date.getDate()}`.slice(-2)

    if (!format) {
      return `${year}年${month}月${day}日`
    }

    return `${year}${format}${month}${format}${day}`
  }
  const formatDateTime = (fmt, date) => {
    let nowDate = date ? new Date(date) : new Date()
    var o = {
      'M+': nowDate.getMonth() + 1, // 月份
      'd+': nowDate.getDate(), // 日
      'h+': nowDate.getHours(), // 小时
      'm+': nowDate.getMinutes(), // 分
      's+': nowDate.getSeconds(), // 秒
      'q+': Math.floor((nowDate.getMonth() + 3) / 3), // 季度
      S: nowDate.getMilliseconds(), // 毫秒
    }
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (nowDate.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    for (var k in o)
      if (new RegExp('(' + k + ')').test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
    return fmt
  }
  const getWeek = () => {
    const dayNumberMap = {
      0: '日',
      1: '一',
      2: '二',
      3: '三',
      4: '四',
      5: '五',
      6: '六',
    }
    const currentDayNumber = new Date().getDay()
    return dayNumberMap[currentDayNumber]
  }
  const getTime = () => {
    let currentHours = new Date().getHours()
    let currentMinutes = new Date().getMinutes()
    if (currentHours < 10) {
      currentHours = `0${currentHours}`
    }
    if (currentMinutes < 10) {
      currentMinutes = `0${currentMinutes}`
    }
    return { hours: currentHours, minutes: currentMinutes }
  }
  const parseNowDate = (type) => {
    const year = new Date().getFullYear()
    let month = new Date().getMonth() + 1
    let day = new Date().getDate()
    if (month < 10) {
      month = '0' + month
    }
    if (day < 10) {
      day = '0' + day
    }

    let nowDate = year + '-' + month + '-' + day
    if (type === 'month') {
      nowDate = `${year}-${month}`
    }

    return nowDate
  }
  return {
    formatDate,
    formatDateTime,
    getWeek,
    getTime,
    parseNowDate,
  }
}
